package com.yhh.college_information_platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.ResultCode;
import com.yhh.college_information_platform.entity.Like;
import com.yhh.college_information_platform.entity.Resource;
import com.yhh.college_information_platform.exception.BusinessException;
import com.yhh.college_information_platform.mapper.LikeMapper;
import com.yhh.college_information_platform.mapper.ResourceMapper;
import com.yhh.college_information_platform.service.LikeService;
import com.yhh.college_information_platform.service.ResourceService;
import com.yhh.college_information_platform.vo.ResourceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 点赞Service实现类
 *
 * @author yhh
 * @date 2025-10-25
 */
@Slf4j
@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceService resourceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLike(Long userId, Long resourceId) {
        log.info("=== 开始点赞 userId={}, resourceId={} ===", userId, resourceId);
        
        // 1. 检查资料是否存在
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "资料不存在");
        }

        // 2. 检查是否已经点赞
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, userId)
                .eq(Like::getResourceId, resourceId);
        Like existLike = likeMapper.selectOne(wrapper);
        
        if (existLike != null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "已经点赞过该资料");
        }

        // 3. 添加点赞记录
        Like like = new Like();
        like.setUserId(userId);
        like.setResourceId(resourceId);
        
        log.info("准备插入点赞记录: userId={}, resourceId={}", like.getUserId(), like.getResourceId());
        log.info("Like对象详情: {}", like);
        
        likeMapper.insert(like);

        // 4. 更新资料的点赞次数
        resource.setLikeCount(resource.getLikeCount() + 1);
        resourceMapper.updateById(resource);

        log.info("用户 {} 点赞了资料 {}", userId, resourceId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeLike(Long userId, Long resourceId) {
        // 1. 查找点赞记录
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, userId)
                .eq(Like::getResourceId, resourceId);
        Like like = likeMapper.selectOne(wrapper);
        
        if (like == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "未点赞该资料");
        }

        // 2. 删除点赞记录
        likeMapper.deleteById(like.getId());

        // 3. 更新资料的点赞次数
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource != null && resource.getLikeCount() > 0) {
            resource.setLikeCount(resource.getLikeCount() - 1);
            resourceMapper.updateById(resource);
        }

        log.info("用户 {} 取消点赞资料 {}", userId, resourceId);
    }

    @Override
    public Boolean isLiked(Long userId, Long resourceId) {
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, userId)
                .eq(Like::getResourceId, resourceId);
        Long count = likeMapper.selectCount(wrapper);
        return count > 0;
    }

    @Override
    public PageResult<ResourceVO> getUserLikes(Long userId, Integer current, Integer size) {
        // 1. 查询用户的点赞记录
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, userId)
                .orderByDesc(Like::getCreateTime);
        
        Page<Like> page = new Page<>(current, size);
        Page<Like> likePage = likeMapper.selectPage(page, wrapper);

        // 2. 获取资料ID列表
        List<Long> resourceIds = likePage.getRecords().stream()
                .map(Like::getResourceId)
                .collect(Collectors.toList());

        // 3. 查询资料详情
        List<ResourceVO> resourceVOList = resourceIds.stream()
                .map(id -> {
                    try {
                        return resourceService.getResourceById(id, userId);
                    } catch (Exception e) {
                        log.warn("获取资料详情失败：{}", id, e);
                        return null;
                    }
                })
                .filter(vo -> vo != null)
                .collect(Collectors.toList());

        return new PageResult<>(resourceVOList, likePage.getTotal(), likePage.getSize(), likePage.getCurrent());
    }
}

